<?php

namespace addons\Asset\common\helpers;

use Yii;
use yii\web\NotFoundHttpException;
use addons\Asset\common\models\Asset;
class ImportHelper
{
    public static $data = '';

    public static function Assets($data, $cate_id=0)
    {
        ini_set('max_execution_time', '0');
        // 开启事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $row=0;
            foreach ($data as $i=>$datum) {
                if (!empty($datum[0])) {
                    $tmp = [
                        'cate_id' => $cate_id,
                        'merchant_id' =>Yii::$app->user->identity->merchant_id,
                        'serial' => $datum[0],
                        'title' => $datum[1],
                        'purchase_price' => $datum[2],
                        'num' => $datum[3],
                        'unit' => $datum[4],
                        'purchase_date' => $datum[5],
                        'person' => $datum[6],
                        'status' => 1,
                    ];
                    $model = new Asset();
                    $model->attributes = $tmp;
//                    Yii::$app->debris->p($tmp);
                    if (!$model->save()) {
                        throw new NotFoundHttpException('第'.$i.'行导入出错，请检查数据格式');
                    }
                }
                else throw new NotFoundHttpException('导入表格数据为空，请核对');
            }

            $transaction->commit();

        } catch (\Exception $e) {
            $row+=$i;
            $transaction->rollBack();
            throw new NotFoundHttpException('第'.$row.'行导入时出错，请检查数据格式');
        }
        return true;
    }

}